import 'dart:convert';
import 'dart:developer';

import 'package:backendview/request/exp.dart';
import 'package:backendview/request/interceptor.dart';
import 'package:backendview/request/response_data.dart';
import 'package:dio/dio.dart' as dio;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class NetworkService extends GetxService {
  static String currentBaseUrl = "http://axrled.nat300.top/AxrLedServer/";
  static final dio.Dio _dio = dio.Dio();
  @override
  void onInit() {
    super.onInit();
    _dio.interceptors.add(MyDioLogger());
  }

  static Future<ResponseData> post(
      {required String url,
      required Map<String, dynamic> map,
      loadingText = "加载中",
      bool showLoading = true,
      useFormData = false}) async {
    if (showLoading) {
      EasyLoading.show(status: loadingText);
    }
    try {
      var res = (await _dio.post("$currentBaseUrl$url",
          options: dio.Options(contentType: "application/json", headers: {}),
          data: useFormData ? dio.FormData.fromMap(map) : map));
      EasyLoading.dismiss();
      log("emmmmm:($url)${jsonEncode(res.data)}");
      var data = ResponseData.fromJson(res.data);
      if (ErrCode.values
          .map((e) => e.value)
          .toList()
          .where((element) => element != ErrCode.apiCorrection.value)
          .contains(data.code)) {
        throw ApiException(code: "${data.code}", message: "${data.message}");
      }
      return data;
    } on ApiException catch (e) {
      EasyLoading.dismiss();
      if (e.code == ErrCode.timeout.value) {
        // todo
      } else {
        EasyLoading.showToast(e.message);
      }
      rethrow;
    } catch (e) {
      throw ApiException(code: ErrCode.apiExp.value, message: "$e");
    }
  }
}
